<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Redis_proxy
{

    //是否长连接
    private $_host = '';
    private $_port = 0;
    private $_auth = '';
    private $_instance = null;
    private $_is_alive = false;


    public function __construct($para = null)
    {
        //获取redis配置信息
        $name = $para['name'] ?? 'default';
        $CI = &get_instance();
        $CI->load->config('redis', true, true);
        $conf = $CI->config->item($name, 'redis');
        if (!$conf || !$conf['host'] || !$conf['port']) {
            log_message('error', ' get redis conf err. name:' . $name);
            return;
        }
        $this->_host = $conf['host'];
        $this->_port = (int)$conf['port'];
        $this->_auth = $conf['auth'];
        //连接redis
        $this->_instance = new Redis();
        $this->_is_alive = $this->_instance->connect($this->_host, $this->_port);
        if (!$this->_is_alive) {
            log_message('error', 'connect redis failed. name:' . $name);
            return;
        }
        if ($this->_auth) {
            $this->_instance->auth($this->_auth);
        }
    }

    public function __call($method, $params)
    {
        if (!$this->_is_alive) {
            log_message('error', 'redis not alive.');
            return [null, 'redis not alive'];
        }
        $rds_res = call_user_func_array(array($this->_instance, $method), $params);
        return [$rds_res, $this->_instance->getLastError()];
    }
}
